package com.xmx.ordercenter.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
@Slf4j
public class FeignConfig {
    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //1.RequestContextHolder拿到当前请求的数据，相当与拿到controller入参的HttpServletRequest
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

                if (requestAttributes!=null){
                    //老请求
                    HttpServletRequest request = requestAttributes.getRequest();

                    if (request!=null){
                        //2.同步请求头信息->Authorization
                        String jwt = request.getHeader("Authorization");
                        log.info("feign header jwt====>{}",jwt);
                        requestTemplate.header("Authorization", jwt);
                    }
                }
            }
        };
    }
}
